const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  // 连接 WebDAV
  connect: (credentials) => ipcRenderer.invoke('webdav-connect', credentials),
  // 断开连接
  disconnect: (username) => ipcRenderer.invoke('webdav-disconnect', username),
  // 获取文件列表
  listFiles: (path) => ipcRenderer.invoke('webdav-list', path),
  // 上传文件
  upload: (localPath, remotePath) => ipcRenderer.invoke('webdav-upload', localPath, remotePath),
  // 新增文件选择对话框
  showSaveDialog: (options) => ipcRenderer.invoke('showSaveDialog', options),
  // 映射为本地磁盘
  mapToSystem: (credentials) => ipcRenderer.invoke('webdav-map-system', credentials),
  // 打开文件
  openFileInSystem: (path) => ipcRenderer.invoke('open-file', path),
  // 创建文件夹
  createDirectory: (options) => ipcRenderer.invoke('create-new-directory', options),
  // 显示右键菜单
  showContextMenu: (params) => ipcRenderer.invoke('show-context-menu', params),
  // 重命名
  rename: (params) => ipcRenderer.invoke('rename', params),
  // 拖拽文件上传完成映射到本地
  dropFileToLocal: (path) => ipcRenderer.invoke('dropFileToLocal', path),
  // 监听操作结果
  onConnectSuccess: (callback) => ipcRenderer.on('connect-success', callback),
  onOperationSuccess: (callback) => ipcRenderer.on('operation-success', callback),
  onOperationError: (callback) => ipcRenderer.on('operation-error', callback),
  oncreateDirectory: (callback) => ipcRenderer.on('create-directory', callback),
  onRename: (callback) => ipcRenderer.on('rename', callback),
  // 取消监听
  removeAllListeners: () => {
    ipcRenderer.removeAllListeners('connect-success');
    ipcRenderer.removeAllListeners('operation-success');
    ipcRenderer.removeAllListeners('operation-error');
    ipcRenderer.removeAllListeners('create-directory');
    ipcRenderer.removeAllListeners('rename');
  },
  // 事件监听（可选，用于接收主进程消息）
  on: (channel, callback) => {
    // 白名单机制，限制可监听的频道
    const validChannels = [
      'webdav-connected', 
      'webdav-disconnected', 
      'permission-changed',
      'webdav-mapped'
    ];
    if (validChannels.includes(channel)) {
      ipcRenderer.on(channel, (_, ...args) => callback(...args));
    }
  }
});